﻿(function () {
    EditTemplateClass = {};
    var arr = [];//当前页面的区域ID集合
    EditTemplateClass.Instance = {
        Init: function () {
            //初始化当前所有的省ID
            var _pids = $("#pid_data").attr("pids");
            arr = _pids.split(',');
            layui.use('form', function () {
                var form = layui.form;
                form.render();
                //自定义验证规则
                form.verify({
                    //验证大于等于0的规则
                    greaterThanZero: function (value, item) {
                        var r = parseFloat(value);
                        if (r < 0)
                            return "必须大于等于0,如不填写请保持默认值0";
                    },
                    //验证金额
                    isMoney: function (value, item) {//这条规则0也会通过，不知道咋改、
                        var pattern = /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/;
                        if (!pattern.test(value))
                            return '金额格式错误,必须大于0并且保留两位小数';
                    }
                });
                form.on('radio(choseType)', function (data) {
                    var value = data.elem.value;
                    switch (value) {
                        case '1':
                            $("#chargeFirstText").text('首件(个)');
                            $("#chargeNextText").text('续件(个)');
                            break;
                        case '2':
                            $("#chargeFirstText").text('首重(kg)');
                            $("#chargeNextText").text('续重(kg)');
                            break;
                    }
                });
                //验证提交
                form.on('submit(add)', EditTemplateClass.Instance.Submit);
            });

            $(document).on('click', '#btnChoseArea', this.ChoseAreas);
            $(document).on('click', '.delitem', this.DelItem);
        },
        DelItem: function () {
            var ids = $(this).attr("idStr");
            var _idsArr = ids.split(',');
            var that = $(this);
            layer.confirm('确定要执行吗？', {
                btn: ['确定', '取消']
            }, function () {
                for (var i = 0; i < _idsArr.length; i++) {
                    arr.remove(_idsArr[i]);//公共ids数组删除
                }
                that.parent().parent().remove();
                layer.closeAll();
            }, function () {

            });

        },
        Submit: function () {
            if (arr.length == 0) {
                layer.alert("请先设置区域运费");
                return false;
            }
            var model = {};
            model.ShippingTemplatesName = $.trim($("#text_shippingTemplatesName").val());
            var chargType;
            $("input[name=text_chargType]").each(function (index, item) {
                if (item.checked)
                    chargType = item.value;
            });
            //$("#input[name=text_status]:checked").val();草他妹的非得用layui的方法来取值
            model.ChargType = chargType;
            model.Items = [];
            model.Id = $(this).attr("st_id");
            $("#charge1Body tr").each(function () {
                var item_model = {};
                item_model.ProvinceIds = $(this).find(".delitem").attr("idStr");
                item_model.ProvinceStr = $(this).find(".batch_areaName").text();
                item_model.FirstValue = $(this).find(".batch_firstvalue").val();
                item_model.FirstAmount = $(this).find(".batch_firstamount").val();
                item_model.NextValue = $(this).find(".batch_nextvalue").val();
                item_model.NextAmount = $(this).find(".batch_nextamount").val();
                model.Items.push(item_model);
            });
            var index = layer.load(1);
            RequestManager.Ajax.Post("/Set/EditTemplate", model, true, function (data) {
                layer.close(index);
                if (data.IsSuccess) {
                    layer.alert("修改成功", function () {
                        window.location.href = "/Set/ShippingTemplateList";
                    });
                    
                } else {
                    layer.alert(data.Message);
                }
            })
        },

        ChoseAreas: function () {
            var iframeIndex = layer.open({
                type: 2,
                area: ['700px', '450px'],
                fixed: false, //不固定
                maxmin: true,
                btn: ['确认选择'],
                yes: function (index, layero) {
                    var _tempIdsArr = [];//选择后临时的区域ID数组，删除时候用到。
                    var areaArr = [];
                    var iframeid = "layui-layer-iframe" + iframeIndex; //获取iframe分配的ID
                    //获取子页面所有勾选框
                    var contens = $("#" + iframeid + "").contents();
                    var checkAreas = $("#" + iframeid + "").contents().find("input[name=check_area]");

                    checkAreas.each(function (index, item) {
                        if (item.checked) {
                            _tempIdsArr.push(item.value);
                            arr.push(item.value);
                            areaArr.push(item.attributes.area.value);
                        }
                    });
                    if (_tempIdsArr.length == 0) {
                        layer.closeAll('iframe');
                        return false;
                    }
                    //拼表格
                    //判断是否是全国
                    var _areaStr = "";

                    if (DataSet.Province.IsAllProvince(_tempIdsArr))
                        _areaStr = "全国";
                    else
                        _areaStr = areaArr.join(',');
                    EditTemplateClass.Instance.CreateTrHtml(_tempIdsArr.join(','), _areaStr);
                    layer.closeAll('iframe');
                },
                content: '/Set/CurrentAreas?ids=' + arr.join(',')
            });
        },
        CreateTrHtml: function (idStr, areaNameStr) {
            var bodyTrArr = [];
            bodyTrArr.push('<tr>');
            bodyTrArr.push('<td class="batch_areaName" style="width:50%">' + areaNameStr + '</td>');
            bodyTrArr.push('<td style="width:10%"><input type="text" class="SkuValueInput2 batch_firstvalue" placeholder="" value="0" lay-verify="required|greaterThanZero"></td>');
            bodyTrArr.push('<td style="width:10%"><input type="text" class="SkuValueInput2 batch_firstamount" placeholder="" value="0" lay-verify="required|isMoney"></td>');
            bodyTrArr.push('<td style="width:10%"><input type="text" class="SkuValueInput2 batch_nextvalue" placeholder="" value="0" lay-verify="required|greaterThanZero"></td>');
            bodyTrArr.push('<td style="width:10%"><input type="text" class="SkuValueInput2 batch_nextamount" placeholder="" value="0" lay-verify="required|isMoney"></td>');
            bodyTrArr.push('<td style="width:10%"> <a class="layui-btn layui-btn-normal layui-btn-xs layui-btn-mini delitem" href="javascript:void(0);"  idStr="' + idStr + '">删除</a></td>');
            bodyTrArr.push('</tr>');

            $("#charge1Body").append(bodyTrArr.join(''));
        }

    };
})();
